package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author zhangyan
 * @date 2021/2/21 10:43
 *
 * @RestController = @Controller + @ResponseBody
 */
@RestController
@RequestMapping("/user")
@Slf4j //相当于在该类中添加了一个变量log
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("/{id}")
        //@PathVariable 将id的值赋给参数id
    public Result findById(@PathVariable Integer id){
        log.debug("findById:" + id);
        User user = userService.findById(id);
        log.info("根据id查询成功!");
        return new Result(true, "查询成功!", user);
    }

    @PostMapping("")
    //RequestBody: 标记在控制器方法的参数上，对post请求体参数进行解析
    public Result add(@RequestBody User user){
        log.debug("add { " + user  +"}");
        userService.add(user);
        return new Result(true, "新增用户数据成功!");
    }

    @GetMapping("")
    public Result findAll(){
        List<User> userList = userService.findAll();
        return new Result(true, "查询成功!",userList);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        log.debug("delete:" + id);
        userService.delete(id);
        return new Result(true, "删除成功!");
    }

    @PutMapping("")
    public Result update(@RequestBody User user){
        log.debug("update:" + user);
        userService.update(user);
        return new Result(true, "修改成功!");
    }
}
